import { store } from "@/store";
import { defineStore } from 'pinia'
import type { userType } from "./types";
import { login, logout, getInfo } from "@/api/user.js";
import Cookies from 'js-cookie';


export const useUserStore = defineStore('pinia-user', {
  state: (): userType => ({ 
    token: Cookies.get('token'),
    name: "",
    grade: "", // 用户等级 1普通用户 2管理员 3超级管理员
    userInfo: {},
    roles: [], 
  }),

  actions: {

    SET_TOKEN(val: String) {
      this.token = val;
      Cookies.set('token', val);
    },

    SET_USERINFO( val: any) {
      this.userInfo = val;
    },
    
    // 登录
    login(userInfo:any) {
      const { username, password } = userInfo;
      return new Promise((resolve, reject) => {
        login({ username: username.trim(), password: password }).then(res => {
          this.SET_TOKEN(res.access_token);
          const { name, avatar, roles } = res.user;
          this.userInfo = res;
          this.name = name;
          this.grade = avatar;
          this.roles = roles
          resolve(res);
          console.log("ok")
        }).catch(error => {
          console.log("失败",error)
          reject(error);
        });
      });
    },

    // 获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          if (!res) {
            reject("Verification failed, please Login again.");
          }
          const { name, avatar, roles } = res;
          this.userInfo = res;
          this.name = name;
          this.grade = avatar;
          this.roles = roles
          resolve(res);
        }).catch(error => {
          reject(error);
        });
      });
    },

    // user logout
    logout() {
      return new Promise((resolve, reject) => {
        logout(this.token).then(() => {
          this.SET_TOKEN("");
          this.roles = []
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },

   
  },
})

export function useUserStoreHook() {
  return useUserStore(store);
}
